// miniprogram/pages/index/index.js
const db = wx.cloud.database()
const db_movements = db.collection('movements')
const app = getApp()
const _ = db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    userShow: false,
    profShow: false,
    actions: [{
      name: '更新用户信息',
      color: '#07c160',
      openType: 'getUserInfo'
    }, ],
    movements: [],
    skip: 0,
    loading: true,
    value: '',
    time: 0,
    username: app.globalData.name,
    nickName: app.globalData.randomName,
    userHead: app.globalData.head,
    myMovementOnly: false,
    colleges: [
      ["传播学院", "media"],
      ["体育部", "sport"],
      ["信息工程学院", "information"],
      ["光电工程学院", "photoelectricity"],
      ["化学与化工学院", "chemistry"],
      ["医学院", "medicine"],
      ["国际交流学院", "international"],
      ["土木工程学院", "construction"],
      ["外国语学院", "language"],
      ["师范学院", "normal"],
      ["建筑与城市规划学院", "building"],
      ["成人教育学院", "adult"],
      ["数学与计算科学学院", "math"],
      ["文学院", "literature"],
      ["机电与控制工程学院", "machine"],
      ["材料学院", "material"],
      ["法学院", "law"],
      ["物理科学与技术学院", "physics"],
      ["生命科学学院", "biology"],
      ["电子科学与技术学院", "eletronic"],
      ["研究生部", "master"],
      ["管理学院", "manage"],
      ["经济学院", "economy"],
      ["艺术设计学院", "art"],
      ["计算机与软件学院", "computer"],
      ["高尔夫学院", "golf"],
    ]
  },

  onLoad: function (options) {
    //console.log(this.data.colleges)
    this.getinit()
    //如果有值，则从全局变量中取值
    if (app.globalData.name && app.globalData.head.length > 0) {
      if (app.globalData.newUser) {
        this.setData({
          userShow: true
        })
        wx.showToast({
          title: '初次见面，请更新您的用户信息',
        })
      }
      this.setData({
        username: app.globalData.name,
        userHead: app.globalData.head,
        nickName: app.globalData.randomName
      })
    } else {
      //如果无值，调用Callback回调函数直接取值
      wx.showToast({
        title: '加载用户信息',
        icon: 'loading'
      })
      app.getSysInfoCallback = res => {
        if (app.globalData.newUser) {
          this.setData({
            userShow: true
          })
          wx.showToast({
            title: '初次见面，请更新您的用户信息',
          })
        }
        this.setData({
          username: app.globalData.name,
          userHead: app.globalData.head,
          nickName: app.globalData.randomName
        })
      }
    }
  },

  onMovement: function (event) {
    console.log(event.currentTarget.dataset.id)
    wx.navigateTo({
      url: '../movementInfo/movementInfo?id=' + event.currentTarget.dataset.id,
    })
  },

  //更新用户信息
  onGetUserInfo(e) {
    if (app.globalData.newUser) {
      db.collection('users').add({
        data: {
          openid: app.globalData.openid,
          name: e.detail.userInfo.nickName,
          randomName: app.globalData.randomName,
          head: e.detail.userInfo.avatarUrl
        }
      }).then(res => {
        wx.cloud.callFunction({
          name: 'updateUser',
          data: {
            name: e.detail.userInfo.nickName,
            head: e.detail.userInfo.avatarUrl,
            openid: app.globalData.openid
          },
          complete: res => {
            this.setData({
              username: e.detail.userInfo.nickName,
              userHead: e.detail.userInfo.avatarUrl,
              userShow: false
            })
            app.globalData.newUser = false
            app.globalData.name = e.detail.userInfo.nickName
            app.globalData.head = e.detail.userInfo.avatarUrl
            wx.showToast({
              title: '欢迎加入树洞',
            })
          }
        })
      })
    }
    wx.cloud.callFunction({
      name: 'updateUser',
      data: {
        name: e.detail.userInfo.nickName,
        head: e.detail.userInfo.avatarUrl,
        openid: app.globalData.openid
      },
      complete: res => {
        this.setData({
          username: e.detail.userInfo.nickName,
          userHead: e.detail.userInfo.avatarUrl,
        })
        app.globalData.name = e.detail.userInfo.nickName
        app.globalData.head = e.detail.userInfo.avatarUrl
        wx.showToast({
          title: '欢迎回到树洞',
        })
      }
    })
  },
  //关闭用户页面
  onUserClose() {
    if (app.globalData.newUser) {
      wx.showToast({
        icon: 'none',
        title: '请更新用户信息以后再进入树洞哦！',
      })
    } else {
      this.setData({
        userShow: false
      });
    }
  },

  onProfClose: function () {
    this.setData({
      profShow: false,
      active: 0,
    });
  },

  //删除树洞按钮
  onDelete: function (event) {
    if (app.globalData.openid != event.currentTarget.dataset.openid) {
      wx.showToast({
        title: '这个树洞不属于你哦',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '删除中',
      })
      wx.cloud.callFunction({
        name: 'deleteMovement',
        data: {
          id: event.currentTarget.dataset.id
        },
        complete: res => {
          this.onLoad()
          wx.hideLoading()
        }
      })
    }
  },

  //观察按钮
  onWatch: function (event) {

  },

  //点赞按钮
  onLike: function (event) {
    console.log(event.currentTarget.dataset.id)
    wx.cloud.callFunction({
      name: 'updateLike',
      data: {
        id: event.currentTarget.dataset.id,
      },
      complete: res => {
        this.onLoad()
      }
    })
  },

  //搜索事件
  onSearch: function () {
    if (!this.data.value) {
      wx.showToast({
        title: '输入值不为空',
        icon: 'none'
      })
      this.getinit()
    }
    db_movements.where({
      text: db.RegExp({
        //以name为关键字进行匹配value
        regexp: this.data.value,
        //输入框输入的内容
        options: 'i',
        //大小写不区分
      })
    }).get().then(res => {
      console.log(res)
      wx.showToast({
        title: '找到' + res.data.length + '条树洞',
      })
      this.setData({
        movements: res.data
      })
    })
  },

  //修改树洞名
  onNameChange: function (event) {
    if (event.detail == '') {
      wx.showToast({
        title: '树洞名不为空',
        icon: 'none'
      })
    }
    if (event.detail.length > 15) {
      wx.showToast({
        title: '树洞名太长了啦！',
        icon: 'none'
      })
    }
  },

  //修改树洞名
  onNameConfirm: function (event) {
    if (app.globalData.newUser) {
      wx.showToast({
        title: '请先跟新您的用户信息哦',
        icon: 'none'
      })
      this.setData({
        nickName: app.globalData.randomName
      })
      return
    }
    if (event.detail == '') {
      wx.showToast({
        title: '树洞名不为空',
        icon: 'none'
      })
      this.setData({
        nickName: app.globalData.randomName
      })
      return
    }
    wx.showLoading({
      title: '正在更新您的树洞名',
    })
    this.setData({
      nickName: event.detail
    })
    app.globalData.randomName = event.detail
    wx.cloud.callFunction({
      name: 'updateUserRandomName',
      data: {
        randomName: event.detail,
        openid: app.globalData.openid
      },
      success: res => {
        wx.hideLoading()
      }
    })
  },

  //下导航栏
  onPageChange(event) {
    // event.detail 的值为当前选中项的索引
    if (event.detail == 0) {
      this.setData({
        active: 0
      })

    }
    if (event.detail == 1) {
      wx.navigateTo({
        url: '../chatList/chatList',
      })
    }
    if (event.detail == 2) {
      this.setData({
        active: 2,
        profShow: true
      })
    }
    if (event.detail == 3) {
      this.setData({
        userShow: true
      })
    }
  },

  //搜索框输入
  onSearchChange(event) {
    // event.detail 的值为当前选中项的索引
    this.setData({
      value: event.detail
    });
  },

  //点击树洞的位置
  onLocation: function (event) {
    console.log(event)
    wx.openLocation(event.currentTarget.dataset.loc)
  },

  //点击树洞图片
  onPicture: function (event) {
    console.log(event)
    wx.previewImage({
      urls: event.currentTarget.dataset.pic // 需要预览的图片http链接列表
    })
  },

  onPlay: function (event) {
    //console.log(event.currentTarget.dataset.sound)
    var innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = event.currentTarget.dataset.sound
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    console.log('#'+event.currentTarget.dataset.id+'count-down')
    var countDown = this.selectComponent('.n'+event.currentTarget.dataset.id+'count-down');
    console.log(countDown)
    countDown.start();
  },

  onCountFinished: function (event) {
    //console.log(event)
    const countDown = this.selectComponent('.n'+event.currentTarget.dataset.id+'count-down');
    countDown.reset();
    countDown.pause();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      myMovementOnly: true
    })
    this.getinit()
    wx.stopPullDownRefresh({
      success: (res) => {},
    })
  },

  onReply: function () {
    if (app.globalData.newUser) {
      wx.showToast({
        title: '请先更新您的用户信息哦',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '../reply/reply',
    })
  },

  onMyMovement: function () {
    if (app.globalData.newUser) {
      wx.showToast({
        icon: 'none',
        title: '请先更新您的用户信息哦',
      })
      return
    }
    this.getMyMovementInit()
    this.setData({
      myMovementOnly: true
    })
  },

  //页面加载我的动态
  getMyMovementInit: function (callback) {
    if (!callback) {
      callback = res => {}
    }
    wx.showLoading({
      title: '加载中'
    })
    var time = new Date().getTime()
    db_movements.where({
      _openid: app.globalData.openid
    }).orderBy('createTime', 'desc').get().then(
      res => {
        //console.log(res.data)
        this.setData({
          movements: res.data,
          skip: res.data.length
        }, res => {
          wx.hideLoading()
          wx.showToast({
            title: '提示：上拉刷新即可重新显示所有人的动态',
            icon: 'none'
          })
          this.setData({
            loading: false,
            time: time
          })
          this.onUserClose()
          callback()
        })
      })
  },

  //到达底部后的加载
  getMyMovementData: function (callback) {
    if (!callback) {
      callback = res => {}
    }
    wx.showLoading({
      title: '加载中',
    })
    var time = new Date().getTime()
    //一次加载默认加载20条记录，会在data.skip变量中加20，下次加载跳过
    db_movements.where({
        _openid: app.globalData.openid
      }).skip(this.data.skip)
      .get().then(res => {
        let oldmovements = this.data.movements
        var skip = this.data.skip + 20
        this.setData({
          movements: oldmovements.concat(res.data),
          time: time,
          skip: skip
        }, res => {
          wx.hideLoading()
          wx.showToast({
            title: '加载成功',
            duration: 500,
          })
          callback()
        })
      })
  },

  //到达页面列表底部
  onReachBottom: function () {
    if (!this.data.myMovementOnly) {
      this.getData()
    } else {
      this.getMyMovementData()
    }
    //云开发Collection.skip
  },

  //页面第一次加载
  getinit: function (callback) {
    if (!callback) {
      callback = res => {}
    }
    wx.showLoading({
      title: '加载中'
    })
    var time = new Date().getTime()
    db_movements.orderBy('createTime', 'desc').get().then(
      res => {
        //console.log(res.data)
        this.setData({
          movements: res.data,
          skip: res.data.length
        }, res => {
          wx.hideLoading()
          wx.showToast({
            title: '加载成功',
          })
          this.setData({
            loading: false,
            time: time
          })
          callback()
        })
      })
  },

  //到达底部后的加载
  getData: function (callback) {
    if (!callback) {
      callback = res => {}
    }
    wx.showLoading({
      title: '加载中',
    })
    var time = new Date().getTime()
    //一次加载默认加载20条记录，会在data.skip变量中加20，下次加载跳过
    db_movements.skip(this.data.skip)
      .get().then(res => {
        let oldmovements = this.data.movements
        var skip = this.data.skip + 20
        this.setData({
          movements: oldmovements.concat(res.data),
          time: time,
          skip: skip
        }, res => {
          wx.hideLoading()
          wx.showToast({
            title: '加载成功',
            duration: 500,
          })
          callback()
        })
      })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '康康树洞里面都藏了神么？',
      path: '/pages/index/index'
    }
  },

  getTimeText: function (timestamp) {
    let current = new Date()
    let before = new Date(timestamp)
    let diff = Math.floor((current - before) / 1000 / 60)
    let time = ''
    if (diff <= 59) {
      time = diff + '分钟前'
    } else if (diff <= 60 * 24 - 1) {
      time = Math.floor(diff / 60) + '小时前'
    } else if (diff <= 60 * 24 * 3 - 1) {
      time = Math.floor(diff / 60 / 24) + '天前'
    } else {
      time = time.split(" ")[0]
    }
    return time
  }
})